/*
 * Copyright (C) 2018 Shanghai Eastsoft Microelectronics Co., Ltd.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author        Notes
 * 2019-01-28     wangyq        the first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include "stdlib.h"
#include "uds/uds_types.h"
#include "uds/uds.h"
#define LED_PIN 39

DiagnosticShims SHIMS;
uint32_t last_can_frame_sent_arb_id;
uint8_t last_can_payload_sent[8];
uint8_t last_can_payload_size;
bool can_frame_was_sent;
#define CAN_DEV_NAME       "can1"      /* CAN ???? */

static struct rt_semaphore rx_sem;     /* ?????????? */
static rt_device_t can_dev;            /* CAN ???? */

#define THREAD_PRIORITY         25
#define THREAD_STACK_SIZE       512
#define THREAD_TIMESLICE        5

static rt_thread_t tid1 = RT_NULL;

DiagnosticResponse last_response_received;
bool last_response_was_received;
bool send_can(const uint32_t arbitration_id, const uint8_t* data,
        const uint8_t size) {
    can_frame_was_sent = true;
    last_can_frame_sent_arb_id = arbitration_id;
    last_can_payload_size = size;
    if(size > 0) {
        memcpy(last_can_payload_sent, data, size);
    }
    return true;
}

void setup() {
    SHIMS = diagnostic_init_shims(0, send_can, NULL);
    memset(last_can_payload_sent, 0, sizeof(last_can_payload_sent));
    can_frame_was_sent = false;
    last_response_was_received = false;
}
int main(void)
{
    int count = 1;
    /* set PC08 pin mode to output */
    rt_pin_mode(LED_PIN, PIN_MODE_OUTPUT);

	setup();
    while (count++)
    {
        rt_pin_write(LED_PIN, PIN_HIGH);
        rt_thread_mdelay(500);
        rt_pin_write(LED_PIN, PIN_LOW);
        rt_thread_mdelay(500);
    }
    return RT_EOK;
}
int can_sample(int argc, char *argv[]) {
    rt_err_t res;
    rt_size_t  size;
    rt_thread_t thread;
    char can_name[RT_NAME_MAX];

    if (argc == 2) {
        rt_strncpy(can_name, argv[1], RT_NAME_MAX);
    } else {
        rt_strncpy(can_name, CAN_DEV_NAME, RT_NAME_MAX);
    }


    can_dev = rt_device_find(can_name);
    if (!can_dev) {
        rt_kprintf("find %s failed!\n", can_name);
        return RT_ERROR;
    }


    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);



    res = rt_device_open(can_dev, RT_DEVICE_FLAG_INT_TX | RT_DEVICE_FLAG_INT_RX);

    res = rt_device_control(can_dev, RT_CAN_CMD_SET_MODE, (void *)RT_CAN_MODE_NORMAL);
    res = rt_device_control(can_dev, RT_CAN_CMD_SET_BAUD, (void *)CAN500kBaud);
    RT_ASSERT(res == RT_EOK);

  ///  thread = rt_thread_create("can_rx", can_rx_thread, RT_NULL, 1024, 25, 10);
    if (thread != RT_NULL) {
        rt_thread_startup(thread);
    } else {
        rt_kprintf("create can_rx thread failed!\n");
    }


    if (size == 0) {
        rt_kprintf("can dev write data failed!\n");
    }

    /* ???? 1,??? thread1,??? thread1_entry*/


    return res;
}

MSH_CMD_EXPORT(can_sample, can device sample);
